import React, { useRef, useEffect, useState } from 'react';
import * as echarts from 'echarts';
import { Card, Radio, Space } from 'antd';

const OrderChart = () => {
  // 图表容器的 DOM 引用
  const chartRef = useRef(null);
  // 图表实例
  let chartInstance = null;

  // 图表数据
  const weekData = [
    { name: '周一', value: 12500 },
    { name: '周二', value: 13800 },
    { name: '周三', value: 11200 },
    { name: '周四', value: 14500 },
    { name: '周五', value: 16800 },
    { name: '周六', value: 19200 },
    { name: '周日', value: 15840 },
  ];

  const monthData = [
    { name: '1日', value: 12500 },
    { name: '5日', value: 14200 },
    { name: '10日', value: 13800 },
    { name: '15日', value: 16500 },
    { name: '20日', value: 18200 },
    { name: '25日', value: 17500 },
    { name: '30日', value: 19800 },
  ];

  // 初始化图表
  const initChart = (data) => {
    // 确保容器已挂载
    if (!chartRef.current) return;

    // 销毁已有实例（避免重复创建）
    if (chartInstance) {
      chartInstance.dispose();
    }

    // 创建图表实例
    chartInstance = echarts.init(chartRef.current);

    // 图表配置
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}: ¥{c}',
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: '#eee',
        borderWidth: 1,
        textStyle: { color: '#333' }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.name),
        axisLine: {
          lineStyle: { color: '#ddd' }
        },
        axisLabel: {
          color: '#666'
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        splitLine: {
          lineStyle: { color: '#f0f0f0' }
        },
        axisLabel: {
          color: '#666',
          formatter: '¥{value}'
        }
      },
      series: [
        {
          data: data.map(item => item.value),
          type: 'bar',
          itemStyle: {
            color: 'rgba(139, 90, 43, 0.7)',
            borderRadius: [4, 4, 0, 0]
          },
          barWidth: '60%'
        }
      ]
    };

    // 设置图表配置
    chartInstance.setOption(option);
  };

  // 响应窗口大小变化
  const handleResize = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  // 时间范围切换
  const [timeRange, setTimeRange] = useState('week');
  
  useEffect(() => {
    // 根据时间范围加载对应数据
    const data = timeRange === 'week' ? weekData : monthData;
    initChart(data);

    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
    
    // 组件卸载时清理
    return () => {
      window.removeEventListener('resize', handleResize);
      if (chartInstance) {
        chartInstance.dispose();
      }
    };
  }, [timeRange]);

  return (
    <Card title="订单金额趋势" className="card-shadow">
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <h3 style={{ margin: 0, color: '#2F4F4F' }}>订单金额趋势</h3>
        <Radio.Group value={timeRange} onChange={(e) => setTimeRange(e.target.value)}>
          <Space>
            <Radio.Button value="week">本周</Radio.Button>
            <Radio.Button value="month">本月</Radio.Button>
          </Space>
        </Radio.Group>
      </div>
      {/* 图表容器 - 必须指定宽高 */}
      <div 
        ref={chartRef} 
        style={{ width: '100%', height: '330px' }}
      />
    </Card>
  );
};

export default OrderChart;
    